package com.xujianlun.cpms.controller.sys;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.common.Response;
import com.xujianlun.cpms.entity.sys.Files;
import com.xujianlun.cpms.mapper.sys.FileMapper;
import com.xujianlun.cpms.service.sys.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @version 1.0
 * @Author xujianlun
 * @Date 2022/11/21 14:31
 * @注释 文件
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.upload.path}")
    private String fileUploadPath;//定义的路径
    //更改的IP地址
    private String getFILE_URL = "http://192.168.31.35:8081/file/";
    @Resource
    private FileMapper fileMapper;
    @Resource
    private IFileService fileService;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws Exception {
        //获取文件原始数据
        String originalFilename = file.getOriginalFilename();
        //获取文件类型
        String extName = FileUtil.extName(originalFilename);
        long size = file.getSize();
//        System.out.println(getFILE_URL);
        //用uid来作为标识位，定义一个文件唯一的标识位
        String uid = IdUtil.fastSimpleUUID();
        //把后缀名extName接上去
        String fileUID = uid + StrUtil.DOT + extName;

        File uploadFile = new File(fileUploadPath + fileUID);

        //先存取到磁盘
        //判断配置的文件目录是否存在，若不存在则创建一个新的目录
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        String md5;
        String url;
        //把获取到的文件存到磁盘目录去
        file.transferTo(uploadFile);
        //当文件存在就获取md5
        // 获取文件的md5 存在 通过对比md5避免上传相同内容的文件
        md5 = SecureUtil.md5(uploadFile);
        // 从数据库查询是否存在相同的记录 查询md
        Files files = getFileMd5(md5);
        //获取URL
        if (files != null) {
            url = files.getUrl();
            //删除已经存的重复文件
            uploadFile.delete();
        } else {
            //如果不存在就不删除上传的文件
            url = getFILE_URL + fileUID;
        }
        //再存取到数据库
        Files fileSave = new Files();
        fileSave.setName(originalFilename);
        fileSave.setType(extName);
        fileSave.setSize(size / 1048576); //除以1024转为kb MB显示
        fileSave.setUrl(url);
        fileSave.setMd5(md5);
        fileMapper.insert(fileSave);
        return url;
    }

    @GetMapping("/{fileUID}")
    public void download(@PathVariable String fileUID, HttpServletResponse response) throws IOException {
        File uploadFile = new File(fileUploadPath + fileUID);

        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    /**
     * 通过文件的md5文件是否存在
     *
     * @param md5
     * @return
     */
    private Files getFileMd5(String md5) {
        //查询md5
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> selectList = fileMapper.selectList(queryWrapper);
        return selectList.size() == 0 ? null : selectList.get(0);
    }

    @GetMapping("/page")
    public IPage<Files> findPage(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam(defaultValue = "") String name) {
        IPage<Files> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        //倒叙
        queryWrapper.orderByDesc("id");
        return fileService.page(page, queryWrapper);
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {
        return Response.success(fileService.removeById(id));
    }

    @PostMapping("/batch/")
    public Response deleteBatch(@RequestBody List<Integer> ids) {
        return Response.success(fileService.removeByIds(ids));
    }

    //启用或者不启用
    @PostMapping("/enable")
    public Response update(@RequestBody Files files) {
        fileMapper.updateById(files);
        return Response.success();
    }
}
